import { filter, find, forEach, includes, map, merge } from 'lodash-es';
import { useRequest } from '@/hooks/requestHooks.js';
// import { useWatch } from '@/hooks/useWatch.js';
import { useGlobalState } from '@/store/globalState.js';
import { dateTypeWatch, runChartWatch, useJCChart } from '@/views/orgMgmt/hooks.js';
import { arrowClassMap } from '@/constants.js';
import { basicTitle, basicLineXAxis, basicLineYAxis, basicLineLegend } from '@/components/chart/options/baseOptions.js';
import {
  getInsDataCount,
  getInsTypeCount,
  getDealTypeCount,
  getBuildingByArea,
  getEngTypesByCode,
  getSubsidyData,
  getType,
  getJCList,
  entEngChartData,
  getAlarmList,
} from '@/api/index.js';

// 机构列表
export const useBuildingList = type => {
  const [buildingList] = useRequest(getBuildingByArea, { defaultParams: [{ projectType: type, isStage: '1' }] });
  return [buildingList];
};
const commonPieOpts = {
  // grid: { bottom: '8%', top: '8%', left: 10 },
  tooltip: {
    trigger: 'item',
    formatter: '占比: {d}%<br />{b}: {c}',
  },
  legend: {
    type: 'scroll',
    show: true,
    orient: 'vertical',
    x: null,
    y: 'center',
    right: 20,
    itemWidth: 10,
    itemHeight: 10,
    itemStyle: { borderWidth: 0 },
  },
  series: [
    {
      name: '',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['40%', '50%'],
      // itemStyle: {
      //   borderRadius: 10,
      //   borderColor: '#fff',
      //   borderWidth: 2,
      // },
      data: [{ name: '', value: '' }],
    },
  ],
};
// 托管/监测-机构分类占比
export const useInsPieChart = type => {
  const extraPieOpts = ref(merge({}, commonPieOpts));
  const [, loading] = useRequest(getInsTypeCount, {
    defaultParams: [{ projectType: type }],
    onSuccess: res => {
      extraPieOpts.value.series[0].data = map(res.data, v => {
        return { name: v.typeName, value: v.num };
      });
    },
  });
  return [extraPieOpts, loading];
};
// 托管-合同类型分类占比
export const useTGDealPieChart = () => {
  const extraPieOpts = ref(merge({}, commonPieOpts));
  const [, loading] = useRequest(getDealTypeCount, {
    defaultParams: [{ projectType: 'TG' }],
    onSuccess: res => {
      const arr = [];
      map(res.data, v => {
        if (v.contractType) arr.push({ name: v.contractType, value: v.projectCount });
      });
      extraPieOpts.value.series[0].data = arr;
    },
  });
  return [extraPieOpts, loading];
};
// 托管-分项总能耗
export const useTGBarChart = () => {
  const params = ref({
    projectType: 'TG',
    isAllInstitution: true,
    buildingCode: '',
  });
  const barExtraOpts = ref({
    color: ['#28c428', '#c86e13', '#6386a8'],
    dataset: {
      dimensions: [
        'amountName',
        { name: 'saving', displayName: '节能量' },
        { name: 'usage', displayName: '实际能耗' },
        { name: 'basic', displayName: '能耗基准' },
      ],
      source: [],
    },
    series: Array.from({ length: 3 }, () => ({
      type: 'bar',
      showSymbol: false,
      smooth: true,
      barWidth: 6,
    })),
    xAxis: merge({}, basicLineYAxis, { axisLabel: { rotate: 30 } }),
    yAxis: merge({}, basicLineXAxis, {
      axisLabel: {
        width: 90,
        color: '#7f889a',
        overflow: 'truncate',
        ellipsis: '...',
      },
    }),
    legend: { show: false },
    grid: { bottom: 0, top: 25, left: 10, right: 20 },
  });
  const displayNameObj = {
    0: {
      // COAL: '总能耗（tce）',
      ELECTRICITY: '电能耗（KWh）',
      WATER: '水能耗（t）',
      AIR: '气能耗（m³）',
      WARM: '暖能耗（kJ）',
    },
  };
  const [, loading, run] = useRequest(getSubsidyData, {
    defaultParams: [params.value],
    onSuccess: res => {
      barExtraOpts.value.dataset.source = map(
        filter(res.data, v => v.energyType !== 'COAL'),
        v => ({
          ...v,
          amountName: displayNameObj['0'][v.energyType],
        }),
      );
    },
  });
  const handleBarChange = val => {
    params.value.isAllInstitution = val ? false : true;
    params.value.buildingCode = val;
    run(params.value);
  };

  return [params, barExtraOpts, loading, handleBarChange];
};
// 监测-机构能耗排名
export const useJCRankChart = rangeType => {
  const activeRank = ref('down');
  const barExtraOpts = ref({
    color: ['#4992ff'],
    dataset: {
      dimensions: ['institutionName', { name: 'institutionValue', displayName: '能耗量' }],
      source: [],
    },
    series: [
      {
        type: 'bar',
        showSymbol: false,
        smooth: true,
        barWidth: 12,
      },
    ],
    xAxis: [
      merge({}, basicLineYAxis, {
        axisLabel: { rotate: 30 },
        nameTextStyle: { align: 'right' },
        nameRotate: -90,
      }),
    ],
    yAxis: [
      merge({}, basicLineXAxis, {
        axisLabel: {
          width: 80,
          color: '#7f889a',
          overflow: 'truncate',
          ellipsis: '...',
        },
      }),
    ],
    legend: { show: false },
    grid: { bottom: 0, top: 25, left: 10, right: 30 },
  });
  const dateRange = ref(rangeType.value.d.default);
  const yearRange = ref({ sYear: null, eYear: null });
  const params = ref({
    belong: '1',
    dateEnd: dateRange.value[1],
    dateStart: dateRange.value[0],
    dateType: 'd',
    energyType: 0,
    projectType: 'JC',
  });
  const [engTypes] = useRequest(getType, {
    defaultParams: [{ all: '1' }],
    onSuccess: () => {
      run(params.value);
    },
  });
  // const [engTypes] = useRequest(getEngTypesByCode, {
  //   defaultParams: [{ enterpriseCode: null, projectType: 'JC', allType: true }],
  //   onSuccess: res => {
  //     if (res.data.length) {
  //       run(params.value);
  //       barExtraOpts.value.xAxis[0].name = `单位：${res.data[0]?.energyUnit ?? ''}`;
  //     }
  //   },
  // });
  const [, rLoading, run] = useRequest(getJCList, {
    defaultParams: [params.value],
    manual: true,
    onSuccess: (res, params) => {
      barExtraOpts.value.dataset.source = res.data ?? [];
      barExtraOpts.value.xAxis[0].name = `单位：${
        find(engTypes.value ?? [], ['id', params[0].energyType])?.energyUnit ?? ''
      }`;
    },
  });
  const handleDaterange = val => {
    params.value.dateStart = val?.[0] ?? null;
    params.value.dateEnd = val?.[1] ?? null;
  };
  const handleYearrange = () => {
    params.value.dateStart = yearRange.value.sYear;
    params.value.dateEnd = yearRange.value.eYear;
  };
  const handleRank = val => {
    activeRank.value = val;
    barExtraOpts.value.dataset.source = barExtraOpts.value.dataset.source.reverse();
  };

  dateTypeWatch(params, dateRange, yearRange, rangeType);
  runChartWatch(params.value, run, false);

  return [
    activeRank,
    dateRange,
    yearRange,
    engTypes,
    params,
    rLoading,
    barExtraOpts,
    handleDaterange,
    handleYearrange,
    handleRank,
  ];
};
// 托管-能耗/收益趋势分析
export const useTGTrendChart = rangeType => {
  const textStyle = {
    color: '#f5f5f5',
    fontWeight: 'normal',
    fontSize: 16,
    lineHeight: 18,
  };
  const commonOpts = {
    title: [
      merge({}, basicTitle, {
        text: '能耗趋势',
        top: 5,
        textStyle,
      }),
      merge({}, basicTitle, {
        text: '收益趋势',
        textStyle,
        top: '53%',
      }),
    ],
    tooltip: {
      formatter: params => {
        if (Array.isArray(params) && params.length > 0) {
          let str = `<div class="u-mb5">${params[0].axisValue}</div>`;
          forEach(params, e => {
            let seriesName = e.seriesName;
            let value = e.value[e.dimensionNames[e.encode.y]] ?? '--';
            if (includes(seriesName, '环比') || includes(seriesName, '同比')) {
              const sign = Math.sign(value);
              value = value !== '--' ? `${value}% <i class="${arrowClassMap.get(sign)} u-fs14"></i>` : `${value}%`;
            }
            str += `<ul class="u-df-spb u-mb5"><li>${e.marker}${seriesName}</li><li class="u-ml30">${value}</li></ul>`;
          });
          return str;
        }
        return '';
      },
    },
    axisPointer: {
      link: { xAxisIndex: 'all' },
    },
    color: ['#4992ff', '#eda422', '#5afe5d', '#f58819', '#26d5d5', '#d5d526', '#5afe5d'],
    xAxis: [
      merge({}, basicLineXAxis, { gridIndex: 0 }),
      { gridIndex: 0, show: false },
      merge({}, basicLineXAxis, { gridIndex: 1 }),
      { gridIndex: 1, show: false },
    ],
    yAxis: [
      merge({}, basicLineYAxis, {
        name: '单位：tce',
        nameTextStyle: { fontSize: 12 },
        gridIndex: 0,
      }),
      merge({}, basicLineYAxis, {
        name: '单位：%',
        nameTextStyle: { fontSize: 12, align: 'right' },
        gridIndex: 0,
      }),
      merge({}, basicLineYAxis, {
        name: '单位：元',
        nameTextStyle: { fontSize: 12 },
        gridIndex: 1,
      }),
      merge({}, basicLineYAxis, {
        name: '单位：%',
        nameTextStyle: { fontSize: 12, align: 'right' },
        gridIndex: 1,
      }),
    ],
    grid: [
      { bottom: 0, top: 80, left: '5%', right: 32, height: '30%' },
      { bottom: 0, top: '65%', left: '5%', right: 32, height: '30%' },
    ],
    dataZoom: null,
  };
  const lineExtraOpts1 = ref(
    merge({}, commonOpts, {
      dataset: [{ dimensions: [] }, { dimensions: [] }],
      legend: [
        {
          ...basicLineLegend,
          data: [],
          x: 'center',
          y: 40,
        },
        {
          ...basicLineLegend,
          data: [],
          x: 'center',
          y: '58%',
        },
      ],
    }),
  );
  const getDimensionsByType = () => {
    return {
      ALL: [
        [
          'energyValueDate',
          { name: 'energyConsumeValue', displayName: '总能耗' },
          { name: 'energyConsumeValueRatio', displayName: '环比' },
        ],
        [
          'energyValueDate',
          { name: 'energyEarningsConservationCost', displayName: '项目总收益' },
          { name: 'energyConservationCostRatio', displayName: '环比' },
        ],
      ],
      CONVENTION: [
        [
          'energyValueDate',
          { name: 'energyBasisValue', displayName: '基准能耗' },
          { name: 'energyConsumeValue', displayName: '实际能耗' },
          { name: 'energyConservationValue', displayName: '节能量' },
          { name: 'energyConservationValueRatio', displayName: '节能率' },
        ],
        [
          'energyValueDate',
          { name: 'energyBasisCost', displayName: '基准费用' },
          { name: 'energyConsumeCost', displayName: '实际费用' },
          { name: 'energyEarningsConservationCost', displayName: '项目收益' },
        ],
      ],
      SHARE: [
        [
          'energyValueDate',
          { name: 'energyConsumeValue', displayName: '实际能耗' },
          { name: 'energyConsumeValueRatio', displayName: '实际能耗环比' },
        ],
        [
          'energyValueDate',
          { name: 'energyEarningsConservationCost', displayName: '综能项目收益' },
          { name: 'energyConservationCostRatio', displayName: '综能项目收益环比' },
        ],
      ],
      ENSURE: [
        [
          'energyValueDate',
          { name: 'energyConsumeValue', displayName: '实际能耗' },
          { name: 'energyConsumeValueRatio', displayName: '实际能耗环比' },
        ],
        [
          'energyValueDate',
          { name: 'energyEarningsConservationCost', displayName: '项目收益' },
          { name: 'energyConservationCostRatio', displayName: '项目收益环比' },
        ],
      ],
    };
  };
  const setSeriesByType = () => {
    let seriesSet = [];
    if (queryParams1.value.contractType === 'CONVENTION') {
      lineExtraOpts1.value.legend[0].data = ['基准能耗', '实际能耗'];
      lineExtraOpts1.value.legend[1].data = ['基准费用', '实际费用'];
      for (let i = 0; i < lineExtraOpts1.value.dataset.length; i++) {
        const item = lineExtraOpts1.value.dataset[i];
        const arr = Array.from({ length: item.dimensions.length - 1 }, (_, idx) => {
          if (idx === 0) {
            const obj = {
              type: 'line',
              smooth: true,
              showSymbol: false,
              lineStyle: { type: 'dashed' },
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 0;
            } else {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 2;
            }
            return obj;
          } else if (idx === 1) {
            const obj = {
              type: 'bar',
              showSymbol: false,
              smooth: true,
              barWidth: 12,
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 0;
            } else {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 2;
            }
            return obj;
          } else {
            const obj = {
              type: 'line',
              symbol: 'none',
              lineStyle: { opacity: 0 },
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 1;
            } else {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 3;
            }
            return obj;
          }
        });
        seriesSet = seriesSet.concat(arr);
      }
    } else {
      for (let i = 0; i < lineExtraOpts1.value.dataset.length; i++) {
        const item = lineExtraOpts1.value.dataset[i];
        const legendArr = map(item.dimensions.slice(1), v => v.displayName);
        lineExtraOpts1.value.legend[i].data = legendArr;
        const arr = Array.from({ length: 2 }, (_, idx) => {
          if (idx === 0) {
            const obj = {
              type: 'bar',
              showSymbol: false,
              smooth: true,
              barWidth: 12,
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 0;
            } else {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 2;
            }
            return obj;
          } else {
            const obj = {
              type: 'line',
              smooth: true,
              showSymbol: false,
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 1;
            } else {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 3;
            }
            return obj;
          }
        });
        seriesSet = seriesSet.concat(arr);
      }
    }
    lineExtraOpts1.value.series = seriesSet;
  };

  const dateRange1 = ref(rangeType.value.d.default);
  const yearRange1 = ref({ sYear: null, eYear: null });
  const commonParams = {
    dateType: 'd',
    energyType: 0,
    contractType: 'ALL',
    projectType: 'TG',
  };
  const queryParams1 = ref(
    merge({}, commonParams, {
      dateEnd: dateRange1.value[1],
      dateStart: dateRange1.value[0],
    }),
  );
  const [, loading1, run1] = useRequest(entEngChartData, {
    defaultParams: [queryParams1.value],
    onSuccess: res => {
      map(getDimensionsByType()[queryParams1.value.contractType], (v, i) => {
        lineExtraOpts1.value.dataset[i].dimensions = v;
        lineExtraOpts1.value.dataset[i].source = res.data;
      });
      setSeriesByType();
    },
  });
  const handleBuildingCode1 = val => {};
  const handleDaterange1 = val => {
    queryParams1.value.dateStart = val?.[0] ?? null;
    queryParams1.value.dateEnd = val?.[1] ?? null;
  };
  const handleYearrange1 = () => {
    queryParams1.value.dateStart = yearRange1.value.sYear;
    queryParams1.value.dateEnd = yearRange1.value.eYear;
  };

  dateTypeWatch(queryParams1, dateRange1, yearRange1, rangeType);
  runChartWatch(queryParams1.value, run1);

  return [
    queryParams1,
    loading1,
    lineExtraOpts1,
    dateRange1,
    yearRange1,
    handleBuildingCode1,
    handleDaterange1,
    handleYearrange1,
  ];
};
// 监测-能耗/碳排趋势分析
export const useJCTrendChart = (rangeType, bool = true) => {
  const [
    dateRangeEC,
    dateRangeCE,
    yearRangeEC,
    yearRangeCE,
    lineExtraOpts1,
    lineExtraOpts2,
    ECParams,
    CEParams,
    ECLoading,
    CELoading,
    handleECDaterange,
    handleCEDaterange,
    handleECYearrange,
    handleCEYearrange,
    runEC,
    runCE,
  ] = useJCChart(rangeType);
  lineExtraOpts1.value.grid = { bottom: 0, top: 50, left: 0, right: 0, containLabel: true };
  lineExtraOpts2.value.grid = { bottom: 0, top: 50, left: 0, right: 0, containLabel: true };
  if (bool) {
    ECParams.value.isHome = true;
    CEParams.value.isHome = true;
    runEC(ECParams.value);
    runCE(CEParams.value);
  }
  const etParams = ref({
    enterpriseCode: null,
    projectType: 'JC',
    allType: bool,
  });
  const [engTypeList, , runEngType] = useRequest(getEngTypesByCode, {
    defaultParams: [etParams.value],
    onSuccess: res => {
      if (res.data.length) {
        ECParams.value.energyType = res.data[0].id;
        lineExtraOpts1.value.yAxis[0].name = `单位：${res.data[0]?.energyUnit ?? ''}`;
      }
    },
  });
  const [engTypeList2, , runEngType2] = useRequest(getEngTypesByCode, {
    manual: true,
    onSuccess: res => {
      if (res.data.length) {
        CEParams.value.energyType = res.data[0].id;
      }
    },
  });
  const changeType = item => {
    lineExtraOpts1.value.yAxis[0].name = `单位：${item?.energyUnit ?? ''}`;
  };
  const handleECBuildingCode = val => {
    etParams.value.enterpriseCode = val;
    runEngType(etParams.value);
  };
  const handleCEBuildingCode = val => {
    etParams.value.enterpriseCode = val;
    runEngType2(etParams.value);
  };

  return [
    dateRangeEC,
    dateRangeCE,
    yearRangeEC,
    yearRangeCE,
    lineExtraOpts1,
    lineExtraOpts2,
    ECParams,
    CEParams,
    ECLoading,
    CELoading,
    engTypeList,
    engTypeList2,
    changeType,
    handleECBuildingCode,
    handleCEBuildingCode,
    handleECDaterange,
    handleCEDaterange,
    handleECYearrange,
    handleCEYearrange,
  ];
};
// 托管/监测-机构数据统计
export const useInsStatics = params => {
  const [staticData, loading] = useRequest(getInsDataCount, { defaultParams: [params] });
  return [staticData, loading];
};
// 实时告警
const jsonParser = blob => {
  let parsed = JSON.parse(blob);
  if (typeof parsed === 'string') parsed = jsonParser(parsed);
  return parsed;
};
export const useRealAlarm = floatRef => {
  // const wsuri = `ws://192.168.140.101:29114/webSocket/${useGlobalState().globalState.userInfo.userid}`;
  // const wsuri = `ws://116.63.97.54:23000/ws/webSocket/${useGlobalState().globalState.userInfo.userid}`;
  let str = window.location.origin + '/prod-api';
  const wsuri = `${str.replace('http', 'ws')}/ws/webSocket/${useGlobalState().globalState.userInfo.userid}`;
  const ws = ref(new WebSocket(wsuri));
  const alarmList = ref({ JC: [], TG: [] });
  ws.value.onmessage = evt => {
    if (evt.data !== '心跳') {
      alarmList.value = jsonParser(evt.data);
      if (alarmList.value.JC.length > 0 || alarmList.value.TG.length > 0) floatRef.value.open = true;
    }
  };
  onBeforeUnmount(() => {
    if (ws.value.readyState === 1) {
      ws.value.close();
      ws.value = null;
    }
  });
  return [alarmList];
};
// 当日告警
export const useAlarmToday = () => {
  const [list] = useRequest(getAlarmList, { defaultParams: [{}] });
  return [list];
};
